﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FHost1
{
    public partial class Site : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies.AllKeys.Contains("fhostuser"))
            {
                pnlAccount.Visible = true;
                pnlLogin.Visible = false;
            }
            else
            {
                pnlAccount.Visible = false;
                pnlLogin.Visible = true;
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                using (FHostDataContext dataContext = new FHostDataContext())
                {
                    List<UserInfo> userInfoList = dataContext.UserInfos.Where(obj => obj.Username == txtLoginUsername.Text.ToLowerInvariant() && obj.Password == txtLoginPassword.Text).ToList();
                    if (userInfoList.Count > 0)
                    {
                        string cookie = string.Format("{0}~{1}", userInfoList[0].UserID, userInfoList[0].FullName);
                        Response.Cookies.Add(new HttpCookie("fhostuser", cookie));
                        Response.Cookies["fhostuser"].Expires = DateTime.Now.AddHours(1);
                        Response.Redirect("MyUploads.aspx");
                    }
                    else
                    {
                        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Invalid username and password!');", true);
                    }
                }
            }
            catch
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Error while login. Please try again after some time!');", true);
            }
        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            Response.Cookies["fhostuser"].Expires = DateTime.Now.AddDays(-1);
            Response.Redirect("Default.aspx");
        }
    }
}